"""
QTableView的测试程序
"""
import sys

from PyQt5 import QtWidgets
from PyQt5 import QtCore  # pylint: disable=W0611
from PyQt5 import QtGui  # pylint: disable=W0611


class QTableViewTest(QtWidgets.QWidget):
    """
    测试的主界面
    """

    def __init__(self, parent=None):
        super(QTableViewTest, self).__init__(parent)

        self.setWindowTitle("QTableViewTest例子")

        self.resize(500, 300)

        self.model = QtGui.QStandardItemModel()
        self.model.setHorizontalHeaderLabels(["标题1", "标题2", "标题3", "标题4"])

        for row in range(4):
            for col in range(4):
                _item = QtGui.QStandardItem("row {}, col {}".format(row, col))
                self.model.setItem(row, col, _item)

        self.tableview = QtWidgets.QTableView()
        self.tableview.setModel(self.model)
        self.tableview.horizontalHeader().setStretchLastSection(True)
        self.tableview.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.Stretch)

        _btn_addrow = QtWidgets.QPushButton("添加")
        _btn_addrow.clicked.connect(self._add_row)

        _btn_show_selection = QtWidgets.QPushButton("当前选中")
        _btn_show_selection.clicked.connect(self._show_selection)

        self.tableview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.tableview.customContextMenuRequested.connect(self._show_menu)

        _h_box_layout = QtWidgets.QHBoxLayout()
        _h_box_layout.addWidget(_btn_addrow)
        _h_box_layout.addWidget(_btn_show_selection)

        dlglayout = QtWidgets.QVBoxLayout()
        dlglayout.addWidget(self.tableview)
        dlglayout.addLayout(_h_box_layout)
        self.setLayout(dlglayout)

    def _show_menu(self, pos):
        index = self.tableview.indexAt(pos)
        value = self.tableview.model().data(index)
        print(value)

    def _add_row(self):
        self.model.appendRow([
            QtGui.QStandardItem("row {}, col {}".format(11, 11)),
            QtGui.QStandardItem("row {}, col {}".format(11, 11)),
            QtGui.QStandardItem("row {}, col {}".format(11, 11)),
            QtGui.QStandardItem("row {}, col {}".format(11, 11))
        ])

    def _show_selection(self):
        # 单选
        # index = self.tableview.currentIndex()
        # print(index.row()+1)
        # 多选
        print("-" * 10)
        indexs = self.tableview.selectionModel().selection().indexes()
        for index in indexs:
            print("line: ", index.row() + 1, index.column() + 1)


if __name__ == '__main__':
    APP = QtWidgets.QApplication(sys.argv)
    QtWidgets.QApplication.setStyle("Fusion")
    WIN = QTableViewTest()
    WIN.show()
    sys.exit(APP.exec_())
